/* JSelect
 * JS操作的基础封装
 * @Jan
 * @Version 2021-0422
 */

let $ = function (select) {
	return new Selector(select);
};

class Selector {
	constructor(select) {
		if (select[0] === "#") {
			// id选择器
			this.select = document.getElementById(select.substr(1));
		}
		this.value = this.getValue();
	}

	/* DOM封装 */
	/* 查 */
	getValue() {
		return this.select.value;
	}

	/* 改 */
	setValue(text) {
		this.select.value = text;
	}
	setText(text) {
		this.select.innerText = text;
	}

	setHtml(html) {
		this.select.innerHTML = html;
	}

	setStyle(style, value) {
		style = style.replace(/-\w/g, function (x) {
			return x.slice(1).toUpperCase();
		});
		this.select.style[style] = value;
	}

	setStyles(styles) {
		for (let key in styles) {
			this.setStyle(key, styles[key]);
		}
	}

	setAttr(attr, value) {
		this.select.setAttribute(attr, value);
	}

	/* 事件处理 */
	on(event, fn) {
		this.select.addEventListener(event, fn);
	}

	click(fn) {
		this.select.addEventListener("click", fn);
	}

	change(fn) {
		this.select.addEventListener("change", fn);
	}
}

class Helper {
	/* 浏览器行为 */
	navigateTo(url) {
		window.location.href = url;
	}

	/* 交互封装 */
	// 显示模态框
	showModal(arg) {
		return new Promise((resolve, reject) => {
			$("#modal").setStyle("display", "flex");
			$("#modal-card").setStyle("display", "block");
			$("#modal-title").setText(arg.title);
			$("#modal-content").setText(arg.content);
			if (arg.confirm == true) {
				console.log("a");
			}
			$("#modal-button").click(() => {
				this.hideModal();
				resolve();
			});
		});
	}

	hideModal() {
		document.getElementById("modal").style.animation = "fade-out 0.8s both";
		document.getElementById("modal-card").style.animation = "fade-up 0.5s reverse";
		setTimeout(() => {
			document.getElementById("modal").style.display = "none";
			document.getElementById("modal-card").style.display = "none";
			document.getElementById("modal").style.animation = "";
			document.getElementById("modal-card").style.animation = "";
		}, 500);
	}
}

let $$ = new Helper();
export { $, $$ };
